<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>农业助手 - Ollama 聊天</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
            background-color: #f5f5f5;
        }

        h1 {
            text-align: center;
            margin-bottom: 20px;
        }

        .chat-box {
            border: 1px solid #ccc;
            height: 400px;
            overflow-y: auto;
            padding: 20px;
            background: white;
            margin-bottom: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 6px rgba(0,0,0,0.1);
        }

        .message {
            display: flex;
            flex-direction: column;
            margin-bottom: 15px;
            align-items: flex-start;
        }

        .user-message, .bot-message {
            max-width: 70%;
            padding: 12px 16px;
            font-size: 15px;
            line-height: 1.5;
            border-radius: 12px;
            word-wrap: break-word;
            position: relative;
            min-width: 100px;
        }

        .user-message {
            background-color: #d1e7dd;
            align-self: flex-end;
            text-align: right;
            color: #2f373a;
            border-bottom-right-radius: 4px;
        }

        .bot-message {
            background-color: #e2e3e5;
            align-self: flex-start;
            color: #2f373a;
            border-bottom-left-radius: 4px;
        }

        input, button {
            padding: 12px;
            font-size: 16px;
            width: 100%;
            margin-top: 10px;
            border-radius: 6px;
            border: 1px solid #ccc;
        }

        @media (max-width: 600px) {
            .user-message, .bot-message {
                max-width: 90%;
            }
        }
    </style>
</head>
<body>
    <div id="navbar" class="mb-6"></div>
    <script>
        fetch('/static/nav.html')
            .then(response => response.text())
            .then(data => {
                document.getElementById('navbar').innerHTML = data;
            })
            .catch(err => console.error('无法加载导航栏:', err));
    </script>

<h1>农业大模型</h1>

<input type="text" id="cityInput" placeholder="请输入城市名（如Tianjin）" />
<div class="chat-box" id="chatBox"></div>
<input type="text" id="userInput" placeholder="请输入你的问题..." />
<button onclick="sendMessage()">发送</button>

<script>
    function parseSimpleMarkdown(text) {
        return text
            .replace(/^###\s(.+)$/gm, '<strong style="color:#2b8a3e;">$1</strong>')
            .replace(/^##\s(.+)$/gm, '<strong style="color:#2b8a3e;">$1</strong>')
            .replace(/^#\s(.+)$/gm, '<strong style="color:#2b8a3e;">$1</strong>')
            .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
            .replace(/^- (.+)/gm, '• $1')
            .replace(/\n/g, '<br>');
    }

    function appendMessage(role, text, dataType = 'internal') {
        const chatBox = document.getElementById("chatBox");

        const msgDiv = document.createElement("div");
        msgDiv.className = "message";

        const innerDiv = document.createElement("div");
        innerDiv.className = role === "user" ? "user-message" : "bot-message";
        innerDiv.innerHTML = parseSimpleMarkdown(text);

        msgDiv.appendChild(innerDiv);
        chatBox.appendChild(msgDiv);
        chatBox.scrollTop = chatBox.scrollHeight;
    }

    function sendMessage() {
        const input = document.getElementById("userInput");
        const city = document.getElementById("cityInput").value.trim();
        const message = input.value.trim();

        if (!message) return;

        appendMessage("user", message);
        input.value = "";

        const loadingMsg = document.createElement("div");
        loadingMsg.className = "bot-message";
        loadingMsg.innerHTML = "<strong>正在获取传感器数据和天气信息...</strong>";
        const loadingContainer = document.createElement("div");
        loadingContainer.className = "message";
        loadingContainer.appendChild(loadingMsg);
        const chatBox = document.getElementById("chatBox");
        chatBox.appendChild(loadingContainer);
        chatBox.scrollTop = chatBox.scrollHeight;

        fetch("/chat_data", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ message: message, city: city })
        })
        .then(res => res.json())
        .then(data => {
            // 删除加载提示
            chatBox.removeChild(loadingContainer);

            // 显示传感器数据
            appendMessage("bot", `### 📊 本地传感器数据\n- 时间: ${data.sensor_data.timestamp}\n- 温度: ${data.sensor_data.temp}°C\n- 湿度: ${data.sensor_data.humidity}%\n- 光照强度: ${data.sensor_data.light} lux`, "internal");

            // 显示天气信息
            appendMessage("bot", `### ☀️ 天气信息\n${data.weather_info}`, "external");

            // 显示回答
            appendMessage("bot", `### 💬 农业建议\n${data.response}`, "external");
        })
        .catch(err => {
            chatBox.removeChild(loadingContainer);
            alert("出错了，请查看控制台日志");
            console.error("请求失败:", err);
        });
    }
</script>

</body>
</html>